package 笔试.华为.线上笔试;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class 层次遍历树 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] source = new int[n];
        for (int i = 0; i < n; i++) {
            source[i] = sc.nextInt();
        }
        TreeNode sourceTree = TreeNode.read(source);
        ArrayList<ArrayList<Integer>> lists = levelOrder(sourceTree);
        for (ArrayList<Integer> list : lists) {
            System.out.println(list);
        }
//        preOrder(sourceTree);
    }

    public static void preOrder(TreeNode root) {
        if (root == null) return;
        System.out.printf("%d ", root.val);
        preOrder(root.left);
        preOrder(root.right);
    }

    public static ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                list.add(poll.val);
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }
            }
            ans.add(list);
        }
        return ans;
    }

    static class TreeNode {
        public int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }

        static public TreeNode read(int[] nums) {
            return readFn(nums, 0);
        }

        static public TreeNode readFn(int[] nums, int i) {
            if (i >= nums.length) {
                return null;
            }
            TreeNode root = new TreeNode(nums[i]);
            root.left = readFn(nums, 2 * i + 1);
            root.right = readFn(nums, 2 * i + 2);
            return root;
        }
    }
}
